package com.lyc.product.servlet;

import com.lyc.product.ServiceImpl.ProductServiceImpl;
import com.lyc.product.bean.Page;
import com.lyc.product.bean.Product;
import com.lyc.product.service.ProductService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

@WebServlet("/bookServlet")
public class ProductServlet extends HttpServlet {
    private ProductService productService=new ProductServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.setCharacterEncoding("UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html");
             String methodName = req.getParameter("methodName");
        try {
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.setAccessible(true);
            // 执行方法
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     doPost(req, resp);
    }
    //得到所有上架书籍列表
   public void getBookList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       List<Product> bookLisst = productService.getBookLisst();
        //把数据放入域中
       req.setAttribute("bookList",bookLisst);
        //进行转发（需要把当前servlet中的HttpServletRequest对象 和HttpServletResponse对象一起转发给请求的资源）
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/js/Product.jsp");//（斜杠表示：根地址：http://tomcat所在的ip:端口/工程名/）
        requestDispatcher.forward(req,resp);
    }

    //得到分页显示的书籍
    public void getBookPageList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int CurrentPageCount=1;
        try{
        CurrentPageCount = Integer.parseInt(req.getParameter("CurrentPageCount"));
        }catch (Exception e){}
        Page<Product> bookListByPage = productService.getBookListByPage(CurrentPageCount);
        req.setAttribute("bookListByPage",bookListByPage);
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/js/Product.jsp");//（斜杠表示：根地址：http://tomcat所在的ip:端口/工程名/）
        requestDispatcher.forward(req,resp);
    }
}
